﻿<template>
  <div class="container myStudent" style="width:99%;margin-top:-25px;">
    <!-- 查询条件 -->
    <div class="query-box query-boxstudent">
      <el-form :model="queryBox" status-icon ref="queryBox">
        <el-row>
          <el-col :span="4">
            <div class="depart-box">
              <div class="slect-title">产品类别</div>
              <el-select clearable filterable v-model="queryBox.product">
                <el-option
                  v-for="item in product_type_options"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <el-form-item label prop="studentCode">
              <el-input v-model="queryBox.studentCode" placeholder="学生编码">
                <template slot="prepend">学生编码</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label prop="name">
              <el-input v-model="queryBox.studentName" placeholder="学生名称">
                <template slot="prepend">学生名称</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="depart-box">
              <div class="slect-title">成单时间</div>
              <el-date-picker
                v-model="createDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <div class="depart-box">
              <div class="slect-title">三方</div>
              <el-select clearable filterable v-model="queryBox.providerThirdParty">
                <el-option
                  v-for="item in SF_options"
                  :key="item.id"
                  :label="item.userName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="depart-box">
              <div class="slect-title">学校</div>
              <el-select clearable filterable v-model="queryBox.providerSchool">
                <el-option
                  v-for="item in school_options"
                  :key="item.id"
                  :label="item.userName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
          <el-form-item label prop="phone">
              <el-input v-model="queryBox.providerClass" placeholder="班级">
                <template slot="prepend">班级</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="11">
            <div class="depart-box">
              <div class="slect-title">成单时间</div>
              <el-date-picker
                v-model="createDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </div>
          </el-col>
        </el-row> -->
        
      </el-form>
      <div class="from-btns">
        <kt-button
          :label="$t('action.reset')"
          perms="true"
          type="primary"
          @click="reset('queryBox')"
        />
        <kt-button :label="$t('action.search')" perms="true" type="primary" @click="search"/>
      </div>
    </div>
    <!--表格内容栏-->
    <div class="btn">
      <Crm-table
        @selectionChange="selectionChange"
        :showBatchDelete="false"
        class="table-width"
        width="400"
        :data="pageResult"
        :columns="columns"
        :loading="loading"
        @findPage="findPage"
        @handleFollow="handleFollow"
        @handleEdit="handleEdit"
        @handleSee="handleSee"
        @handleoutbound="handleoutbound"
        @handleOrder="handleOrder"
      ></Crm-table>
    </div>  
  </div>
</template>
<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import KtButton from "@/views/Core/KtButton";
import CrmTable from "@/views/Core/CrmTable";
import CrmSwitch from "@/views/Core/CrmSwitch";
import { CodeToText } from "element-china-area-data";
import { baseUrl } from "@/utils/global";
import Cookies from "js-cookie";
import { regionDataPlus } from "element-china-area-data";
import axios from "axios";
import store from "@/store";
import { isMobile } from "@/utils/validate";
import { mapActions } from "vuex";
import CrmPermsBox from "@/views/Core/Crmpermsbox";
// 索要
import Askingfor from "@/views/Core/Askingfor";
export default {
  name: "Student",
  components: {
    PopupTreeInput,
    CrmTable,
    KtButton,
    CrmSwitch,
    CrmPermsBox,
    Askingfor
  },
  data() {
    return {
      aa: true,
      selectDisabled: false, //跟进弹窗客户进展状态
      typeDisabled: false,
      checkedPeson: 0,
      student_import_department: [],
      size: "mini",
      gradeCache: [],
      // filters: {
      //   name: ""
      // },
      // 查询条件
      student_data_from_options: [
        {
          label: " ",
          key: " "
        }
      ],
      mytime: "",
      showBatchDelete: false,
      // 客户跟进数据
      stuqueryTrackingData: {
        content: []
      },
      pageRequest2: {
        pageNum: 1,
        pageSize: 10
      },
      studentContractType_options: [],
      student_type_options: [],
      student_progress_options: [
        {
          label: " ",
          key: " "
        }
      ],
      isTodayTracking_options: [
        {
          value: "是",
          label: "1"
        }
      ],

      student_data_from_type_options: [
        {
          label: " ",
          key: " "
        }
      ],
      assignDate: "",
      grade_cache_gradeOptions: [],
      queryBox: {
        name: "",
        dataFrom: "",
        type: "",
        dataFromType: "",
        progress: "",
        code: "",
        phone: "",
        school: "",
        providerTeacher: "",
        providerAgent: "",
        createDate: "",
        moveDate: "",
        belongToPerson: "",
        pageNum: 0,
        pageSize: 0,
        importDepartment: "",
        grade: "",
        isCheckRecycleDate:'',
        providerThirdParty:'',
        providerSchool:'',
        providerClass:''
      },
      width: 200,
      columns: [
        { type: "index", label: "序号", minWidth: 50 },
        { prop: "orderId", label: "订单号", minWidth: 150 },
        { prop: "studentCode", label: "学生编码", minWidth: 150 },
        { prop: "studentName", label: "学生姓名", minWidth: 120 },
        { prop: "grade", label: "年级", minWidth: 80 },
        { prop: "product", label: "产品类型", minWidth: 100 },
        { prop: "providerThirdParty", label: "三方", minWidth: 100 },
        { prop: "providerSchool", label: "学校", minWidth: 100 },
        { prop: "providerClass", label: "班级", minWidth: 100 },
        { prop: "money", label: "金额", minWidth: 70 },
        { prop: "signDate", label: "成单时间", minWidth: 150 },
        { prop: "classNum", label: "课时数", minWidth: 80 },
        { prop: "isReturn", label: "是否退单", minWidth: 100 },
      ],
      columns2: [
        { type: "index", label: "序号", minWidth: 10 },
        { prop: "contractDate", label: "跟进时间", minWidth: 100 },
        { prop: "contactPeople", label: "联系人", minWidth: 50 },
        { prop: "trackingPeople", label: "跟进人", minWidth: 50 },
        { prop: "contractType", label: "沟通形式", minWidth: 50 },
        { prop: "contractResult2", label: "沟通结果", minWidth: 50 },
        { prop: "customerType", label: "客户类型", minWidth: 80 },
        { prop: "getprogress", label: "客户进展", minWidth: 50 },
        { prop: "contractContent", label: "沟通内容", minWidth: 120 },
        { prop: "creater", label: "跟进人", minWidth: 50 },
        { prop: "nextContractDate", label: "下次跟进时间", minWidth: 100 }
      ],

      pageResult: {
        content: []
      },

      isTodayTracking: "",
      student_type_options: [],
      operation: true, // true:新增, false:编辑
      batchdistribution: false, //显示批量分配弹窗
      customerownership: false, //显示客户归属弹窗
      addFollow: false, //显示跟进窗口
      selectionsLength: "",
      deptTreeProps: {
        label: "name",
        children: "children"
      },
      roles: [],
      selections: [], //选中列表集合
      ids: [], //分配ID集合
      ids2: [],
      deptData: [], //部门树
      deptTree: {
        label: "deptName",
        children: "children"
      },
      timer: null,
      deptinputValue: "",
      // 划分方式
      deptmodeoptions: [
        {
          label: "分配至部门",
          value: "11"
        },
        {
          label: "分配至个人",
          value: "9"
        }
      ],
      deptmodeoptionsValue: "",
      submitID: "",
      deptId: "",
      userID: "", //人员ID
      deptuseroption: [], //部门用户
      deptuseroptionValue: "",
      branchcenter: [], //分中心下拉
      branchcenterValue: "",
      branchcenterValueID: "",
      branchcenterCodeValue: "", //分中心编码
      addstuformData: {},
      student_type_options: [],
      student_tracktype_options: [],
      TQtoken_init: "",
      phone: "",
      demo: browserfly.noConflict(),
      // 呼叫信息
      callDate: "", //呼叫时间
      call: "",
      timeLength: "", //通话时长
      tqCode: "", //通话的TQ号
      isGetThrough: "", //是否接通
      contractPeople: "", //联系人
      seatCode: "", //坐席号
      student: "", //呼叫的学生ID
      callState: "", //挂断方式
      uploadOem: false, //文件上传
      limitNum: 1, //上传最大个数
      form: {
        file: ""
      },
      baseUrl: baseUrl,
      fileList: [],
      uploadUrl: baseUrl + "/file/upload", //文件上传地址
      downloadTmplUrl: baseUrl + "/template/studentImportTemplate.xlsx", //模板下载地址
      stuTableData: {
        studentInfo: {
          trackingNum: 0
        }
      },
      saveData: {
        customerType: "",
        contractDate: "",
        customerProgress: "",
        contractContent: "",
        nextContractDate: "",
        contactPeople: "",
        contractType: "",
        contractResult: "",
        studentId: this.$route.query.id,
        phoneAdress: "",
        sparePhoneAdress:"",
        source:'',
        importDepartment:'',
        grade:''
      },
      trackingPeople: Cookies.get("realName"),
      student_communication_type: [],
      // 分中心名称
      restaurants: [],
      branchCenterName: "",
      userName: "",
      createDate: "",
      trackingDate: "",
      //   地区
      options: regionDataPlus,
      selectedOptions: [],
      loading: false, // 加载标识
      nextTrackingDate: "", //应跟进时间
      // 限制跟进时间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
      date: new Date(),
      student_result_options: [],
      student_progress_options2: [],
      reportType_options: [],
      reportResult_options: [],
      subject_Options: [],
      comment: "",
      student_import_department: [],
      askingforShow:false,
      askingloading:false,
      askingMessage:'',
      isLoadingSuccess:false,//是否索要成功
      roleId: "", //当前登录用户的角色id
      // roleId1: "307922416041209975", //咨询师
      // roleId2: "307922480151146627", //直销三级部门管理
      // roleId3: "307922544034590863", //直销部门管理
      // roleId4: "318843899038940998", //金丰和校区管理
      // roleId5: "318845886098849661", //金丰和班主任管理
      hideSome:false,
      isSpareChange:false,
      product_type_options:[
        {
          key:'1',
          value:'录播课'
        },
        {
          key:'2',
          value:'学酷一对一'
        },
        {
          key:'3',
          value:'课糖'
        },
      ],
      isSpareChange:false,
      SF_options:[]
    };
  },
  methods: {
    // 搜索
    search() {
      this.loading = true;
      if (this.createDate != null) {
        this.queryBox.createDateStart = this.createDate[0];
        this.queryBox.createDateEnd = this.createDate[1];
      } else {
        this.queryBox.createDateStart = "";
        this.queryBox.createDateEnd = "";
      }

      this.queryBox.province = this.selectedOptions[0];
      this.queryBox.city = this.selectedOptions[1];
      this.queryBox.area = this.selectedOptions[2];
      if (this.nextTrackingDate != null) {
        this.queryBox.nextTrackingDateStart = this.nextTrackingDate[0];
        this.queryBox.nextTrackingDateEnd = this.nextTrackingDate[1];
      } else {
        this.queryBox.nextTrackingDateStart = "";
        this.queryBox.nextTrackingDateEnd = "";
      }
      if (this.assignDate != null) {
        this.queryBox.assignDateStart = this.assignDate[0];
        this.queryBox.assignDateEnd = this.assignDate[1];
      } else {
        this.queryBox.assignDateStart = "";
        this.queryBox.assignDateEnd = "";
      }

      this.pageRequest.pageNum = 1;
      this.findPage(null);
    },
    // 获取分页数据
    findPage: function(data) {
      if (data !== null) {
        this.loading = true;
        this.pageRequest = data.pageRequest;
      }
      this.queryBox.pageSize = this.pageRequest.pageSize;
      this.queryBox.pageNum = this.pageRequest.pageNum;
      this.queryBox.branchCenterId=Cookies.get("userId");
      
      if (this.queryBox.isCheckRecycleDate == "1" ) {
        this.pageRequest = Object.assign({}, this.pageRequest, this.queryBox, {
          type:1// 当筛选项选择了紧急回访客户  type传1
        });
      } else {
        this.pageRequest = Object.assign({}, this.pageRequest, this.queryBox)
      }
      this.$api.student
        .querySignInfo(this.pageRequest)
        .then(res => {
          let content = { content: res.listStudentSignInfo, totalSize: res.total };
          this.pageResult = content;
          this.pageResult.content.forEach(item => {
            if(item.product==1){
              item.product='录播课'
            }else  if(item.product==2){
              item.product='学酷一对一'
            }else  if(item.product==3){
              item.product='课糖'
            }
            item.isReturn==1?item.isReturn='退单':item.isReturn='未退单'
            if (item.province == null || item.province == "null") {
              item.diqu = "";
            } else if (
              (item.province != null && item.city == null) ||
              (item.province != "null" && item.city == "null")
            ) {
              item.diqu = CodeToText[item.province];
            } else if (
              (item.province != null &&
                item.city != null &&
                item.area == null) ||
              (item.province != "null" &&
                item.city != "null" &&
                item.area == "null")
            ) {
              item.diqu = CodeToText[item.province] + CodeToText[item.city];
            } else if (
              (item.province != null &&
                item.city != null &&
                item.area != null) ||
              (item.province != "null" &&
                item.city != "null" &&
                item.area != "null")
            ) {
              item.diqu =
                CodeToText[item.province] +
                CodeToText[item.city] +
                CodeToText[item.area];
            }
            this.student_data_from_options.forEach(type_item => {
              if (type_item.key == item.dataFrom) {
                item.laiyuan = type_item.value;
              }
            });
            this.student_progress_options.forEach(progress_item => {
              if (progress_item.key == item.progress) {
                item.getprogress = progress_item.value;
              }
            });
            // 获取方式对应
            this.student_data_from_type_options.forEach(data_from_type_item => {
              if (data_from_type_item.key == item.dataFromType) {
                item.getType = data_from_type_item.value;
              }
            });
            // 客户类型对应
            this.student_type_options.forEach(student_type_item => {
              if (student_type_item.key == item.type) {
                item.type = student_type_item.value;
                item.customerType = student_type_item.key;
              }
            });
            //年级
          // consloe.log(this.gradeCache)
          //   this.gradeCache.forEach(gradeItem => {
          //     if (gradeItem.fId == item.grade) {
          //       item.gradeInfo = gradeItem.fGradeName;
          //     }
          //   });
            //报告类型转义
            this.reportType_options.forEach(reportTypeItem => {
              if (reportTypeItem.key == item.reportType) {
                item.reportType2 = reportTypeItem.value;
              }
            });
            //报告结果转义
            this.reportResult_options.forEach(reportResultItem => {
              if (reportResultItem.key == item.reportResult) {
                item.reportResult = reportResultItem.value;
              }
            });
            // 学科
            this.studentSubject.forEach(subItem => {
              if (subItem.fId == item.subject) {
                item.subject = subItem.fSpecialtyName;
              }
            });
            // 导入部门转换
            this.student_import_department.forEach(subItem => {
              if (subItem.key == item.importDepartment) {
                item.importDepartment = subItem.value;
              }
            });
            // 转换推广来源
              this.student_TGsource_options.forEach(TGsourceItem => {
                if (TGsourceItem.key == item.source) {
                  item.source = TGsourceItem.value;
                }
              });
              this.SF_options.forEach(SFItem=>{
                if(item.providerThirdParty==SFItem.id){
                  item.providerThirdParty=SFItem.userName
                }
              })
              this.school_options.forEach(SCItem=>{
                if(item.providerSchool==SCItem.id){
                  item.providerSchool=SCItem.userName
                }
              })
          });
          this.loading = false;
        })
        .then(data != null ? data.callback : "");
    },

    // 重置
    reset(queryBox) {
      this.loading = true
      this.$refs.queryBox.resetFields();
      this.queryBox.studentCode = "";
      this.queryBox.studentName = "";
      this.queryBox.product = "";
      this.createDate=[]
      this.queryBox.createDateStart = "";
      this.queryBox.createDateEnd = "";
      this.queryBox.providerThirdParty=""
      this.queryBox.providerSchool=""
      this.queryBox.providerClass=""
      this.findPage(null);
    },
    // 批量删除
    handleBatchDelete() {
      this.ids2 = [];
      let idstu2 = this.selections.map(item => item.id);
      // this.dataFormAdd = Object.assign({}, params.row);
      this.ids2 = idstu2;
      this.$confirm(
        "确认删除" + this.selections.length + "个客户吗？",
        "提示",
        {}
      ).then(() => {
        this.editLoading = true;
        this.$api.student
          .studentAssignResourceAssign({
            listStudentId: this.ids2,
            belongType: 13
          })
          .then(res => {
            if (res.result == 2) {
              this.$message({
                message: res.msg,
                type: "error"
              });
            } else {
              this.findPage(null);
            }
          });
      });
    },
    // 查看客户档案
    handleSee: function(params) {
      this.dataForm = Object.assign({}, params.row);
      this.$router.push({
        path: "/Customerfile/Student",
        query: {
          id: this.dataForm.id
        }
      });
    },
    // 报单跳转
    handleOrder(params) {
      this.getOrder();
    },
    // 新增客户
    handleNewADD: function() {
      this.$router.push({
        path: "/Customerfile/AddStudent",
        query: {
          name: "schoolResources"
        }
      });
    },
    // 客户跟进
    handleFollow: function(params) {
      this.addFollow = true;
      this.saveData.trackingNum = params.row.trackingNum;
      this.saveData.name = params.row.name;
      this.saveData.contactPeople = params.row.name;
      this.saveData.contractType = "1";

      this.saveData.customerType = params.row.customerType;

      if (params.row.progres == "8") {
        this.saveData.customerProgress = "已成单";
      } else if (params.row.progress == "2") {
        this.saveData.customerProgress = "";
      } else if (params.row.progress == "1") {
        this.saveData.customerProgress = "";
      } else if (params.row.progress == "5") {
        this.saveData.customerProgress = "";
      } else if (params.row.progress == "9") {
        this.saveData.customerProgress = "";
      } else {
        this.saveData.customerProgress = params.row.progress;
      }
      this.studentQueryInfo(params.row.id);
      this.saveData.importDepartment = params.row.importDepartment;
      this.saveData.source=params.row.source
      this.saveData.studentId = params.row.id;
      this.saveData.pageAddress = params.row.pageAddress;
      this.saveData.keyWords = params.row.keyWords;
      this.saveData.phone = params.row.phone;
      this.saveData.contractDate = this.dateFormat(new Date());
      this.pageRequest2.pageNum = "1";
      this.saveData.reportType2 = params.row.reportType2;
      this.saveData.reportType = params.row.reportType;
      this.saveData.reportResult = params.row.reportResult;
      this.saveData.grade = params.row.grade;
      this.saveData.diqu = params.row.diqu;
      this.saveData.sparePhone=params.row.sparePhone
      this.old=params.row.grade
      this.$api.student
        .queryCallAddress({ phone: params.row.phone })
        .then(res => {
          let jsonObj = JSON.parse(res.msg).response;
          let address = [];
          var arr = [];
          for (let i in jsonObj) {
            arr.push(jsonObj[i]); //属性
          }
          this.saveData.phoneAdress = arr[0].location;
        });
      if(params.row.sparePhone!=null){
          this.$api.student
          .queryCallAddress({ phone: params.row.sparePhone })
          .then(res => {
            let jsonObj = JSON.parse(res.msg).response;
            let address = [];
            var arr = [];
            for (let i in jsonObj) {
              arr.push(jsonObj[i]); //属性
            }
            this.saveData.sparePhoneAdress = arr[0].location;
          });
          this.isSpareChange=true
      }else{
        this.isSpareChange=false
      }
      this.get_result();
      this.trackingStuId = params.row.id;
      this.trackingStuPhone = params.row.phone;
      this.trackingSparePhone = params.row.sparePhone
      this.findPage2(null);
    },
    // 更新备用电话
    updateField(params){
      let phone2=this.saveData.sparePhone
      let dataItem={
        id:this.saveData.studentId,
        sparePhone:this.saveData.sparePhone
      }
      if(!this.isSpareChange){
        if(phone2==''||phone2==null){
          this.handleSave()
        }else{
          if(phone2!=undefined&phone2!=''){
            if(!isMobile(phone2)){
              this.$message({
                  message: '请输入正确的备用手机号！',
                  type: "error"
                });
              return  false
            }
            this.$api.student.updateField(dataItem).then(res=>{
              if(res.result==2){
                this.$message({
                  message: res.msg,
                  type: "error"
                });
                return false
              }
              this.handleSave()
            })
          }
        }
      }else{
        this.handleSave()
      }
    
    },
    // 保存跟进数据
    handleSave() {
      let phone2=this.saveData.sparePhone
      let dataItem={
        id:this.saveData.studentId,
        sparePhone:this.saveData.sparePhone
      }
      this.$api.student.addstudentTracking(this.saveData).then(res => {
        if (res.result != 1) {
          this.$message({
            message: res.msg,
            type: "error"
          });
        } else {
          
          this.$message({
            message: res.msg,
            type: "success"
          });
          this.addFollow = false;
          this.saveData.customerProgress = "";
          this.saveData.customerType = "";
          this.saveData.contractContent = "";
          this.saveData.nextContractDate = "";
          this.saveData.contractType = "";
          this.saveData.contactPeople = "";
          this.saveData.contractResult = "";
          this.comment = "";
          this.findPage(null);
        }
      });
    },
    // 查询学生跟进列表
    findPage2(data) {
      if (data !== null) {
        this.loading = true;
        this.pageRequest2 = data.pageRequest;
      }
      this.$api.student
        .queryStudentTrackingList({
          studentId: this.saveData.studentId,
          pageSize: this.pageRequest2.pageSize,
          pageNum: this.pageRequest2.pageNum
        })
        .then(res => {
          let content = {
            content: res.listStudentTrackingInfo,
            totalSize: res.total
          };

          this.stuqueryTrackingData = content;
          this.loading = false;
          this.stuqueryTrackingData.content.forEach(item => {
            // 进展转换
            this.student_progress_options.forEach(progress_item => {
              if (progress_item.key == item.customerProgress) {
                item.getprogress = progress_item.value;
              }
            });
            // 类型转换
            this.student_type_options.forEach(type_item => {
              if (type_item.key == item.customerType) {
                item.customerType = type_item.value;
              }
            });
            // 沟通形式转换
            this.studentContractType_options.forEach(communication_item => {
              if (communication_item.key == item.contractType) {
                item.contractType = communication_item.value;
              }
            });

            // 沟通结果转换
            this.student_result_options.forEach(result_item => {
              if (result_item.key == item.contractResult) {
                item.contractResult2 = result_item.value;
              }
            });
          });
        })
        .then(data != null ? data.callback : "");
    },
    // 获取客户档案（备注）
    studentQueryInfo(params) {
      this.$api.student.studentQueryInfoWithEscape({ id: params }).then(res => {
        if (res.result == 1) {
          this.comment = res.studentInfoAttr.comment;
        }
      });
    },
    // 获取选中的表格数据
    selectionChange: function(selections) {
      this.selections = selections.selections;
    },
    // 修改客户档案
    handleEdit: function(params) {
      this.dataForm = Object.assign({}, params.row);
      // console.log(params.row)
      this.$router.push({
        path: "/Customerfile/EditStudent",
        query: {
          id: this.dataForm.id
        }
      });
    },
    // 菜单树选中
    handleOptionClick() {},
    // 获取来源
    get_student_data_from() {
      this.student_data_from_options = JSON.parse(
        localStorage.getItem("studentSource")
      );
      this.SF_options = JSON.parse(
        localStorage.getItem("SFcacheList")
      );
      this.school_options = JSON.parse(
        localStorage.getItem("SchoolcacheList")
      );
    },
    // 获取进展
    get_student_progress() {
      this.student_progress_options = JSON.parse(
        localStorage.getItem("studenProgress")
      );
    },
    student_progress_change(value) {
      this.queryBox.student_progressValue = value.toString();
    },
    get_student_type() {
      this.$api.user.optionsList({ codeType: "student_type" }).then(res => {
        this.student_type_options = res.keyValueList;
      });
    },
    
    // 获取跟进客户类型
    get_student_track_type() {
      
      this.student_tracktype_options = JSON.parse(
        localStorage.getItem("stdentTpye")
      );
    },
    get_student_data_from_type() {
      this.student_data_from_type_options = JSON.parse(
        localStorage.getItem("stdentDataFromType")
      );
    },
    student_parent_type_change(value) {
      this.info.studentInfoDetail.studentInfoAttr.parentType = value.toString();
    },
    // 获取沟通类型
    get_studentContractType() {
      this.studentContractType_options = JSON.parse(
        localStorage.getItem("studentContractType")
      );
    },
    // 获取年级
    get_grade_cache() {
      this.grade_cache_gradeOptions = JSON.parse(
        localStorage.getItem("gradeCache")
      );
    },
    gradeChange(item) {
      this.queryBox.grade = item.fId;
    },
    gradeChange2(item) {
      this.saveData.grade = item;
      // this.saveData.grade = item.fId;
    },
    // 点击外呼
    handleoutbound(params) {
      let studentId = params.row.id;
      this.student = params.row.id;
      this.phone = params.row.phone;
      this.$api.user
        .callOut({
          op: "makecall",
          phone: this.phone,
          uin: Cookies.get("uin"),
          adminUin: Cookies.get("admin_uin"),
          token: Cookies.get("tqToken")
        })
        .then(res => {
          if (res.result == 2) {
            this.$message({
              message: res.msg,
              type: "error"
            });
          } else {
            this.$message({
              message: "外呼成功！",
              type: "success"
            });
          }
        });
      const makeCallCallBack = function(ret, jsonObject) {
        // console.log(JSON.stringify(ret));
      };
    },

    // 跟进弹窗外呼
    handleoutbound2(params) {
      this.student = this.trackingStuId;
      this.$api.user
        .callOut({
          op: "makecall",
          phone: this.trackingStuPhone,
          uin: Cookies.get("uin"),
          adminUin: Cookies.get("admin_uin"),
          token: Cookies.get("tqToken")
        })
        .then(res => {
          if (res.result == 2) {
            this.$message({
              message: res.msg,
              type: "error"
            });
          } else {
            this.$message({
              message: "外呼成功！",
              type: "success"
            });
          }
        });
      const makeCallCallBack = function(ret, jsonObject) {
        // console.log(JSON.stringify(ret));
      };
    },
    // 跟进窗口外呼备用电话
    handleoutbound3(params) {
      this.student = this.trackingStuId;
      if(isMobile(this.trackingSparePhone)){
          this.$api.user
          .callOut({
            op: "makecall",
            phone: this.trackingSparePhone,
            uin: Cookies.get("uin"),
            adminUin: Cookies.get("admin_uin"),
            token: Cookies.get("tqToken")
          })
          .then(res => {
            if (res.result == 2) {
              this.$message({
                message: res.msg,
                type: "error"
              });
            } else {
              this.$message({
                message: "外呼成功！",
                type: "success"
              });
            }
          });
        const makeCallCallBack = function(ret, jsonObject) {
          // console.log(JSON.stringify(ret));
        };
      }else{
        this.$message({
          message: '电话号码不正确！',
          type: "error"
        });
      }
    },

    wac() {
      // 监听通话事件
      this.demo.monitorEvent(
        "callEvent",
        function(message, jsonObject) {
          // console.log("监控通话事件"+this.student)
          // 时间转化
          function timestampToTime(timestamp) {
            let date = new Date(timestamp / 1000);
            var Y = date.getFullYear() + "-";
            var M =
              (date.getMonth() + 1 < 10
                ? "0" + (date.getMonth() + 1)
                : date.getMonth() + 1) + "-";
            var D = date.getDate() + " ";
            var h = date.getHours() + ":";
            var m = date.getMinutes() + ":";
            var s = date.getSeconds();
            return Y + M + D + h + m + s;
          }
          let callDate = timestampToTime(message.call_event.create_time);
          // 通话时长
          let timeLength = (
            (message.call_event.hangup_time - message.call_event.answer_time) /
            1000000
          ).toFixed(0);
          if (timeLength >= 10) {
            this.is_answer = 1;
            timeLength;
          } else {
            this.is_answer = 2;
            timeLength = 0;
          }
          // 提交给服务器
          if (message.call_event.call_state == "agent_hangup") {
            axios
              .post(baseUrl + "/studentCall/call", {
                callDate: callDate, //呼叫时间
                timeLength: timeLength, //通话时长
                tqCode: Cookies.get("uin"), //通话的TQ号
                isGetThrough: this.is_answer, //是否接通1接通  2未接通
                seatCode: message.call_event.seat_dbid, //坐席号
                studentId: this.student //呼叫的学生ID
              })
              .then(res => {
                this.findPage(null);
              });
            console.log("挂机");
          }
        }.bind(this)
      );
    },
    // 初始化TQ
    get_tqToken() {
      const admin_uin = Cookies.get("admin_uin");
      const uin = Cookies.get("uin");
      const strid = "";
      const appid = Cookies.get("appid");
      const appkey = Cookies.get("appkey");
      const ct = Math.round(new Date().getTime() / 1000).toString();
      const sign2 = hex_md5(appid + "*(**)*" + appkey).toUpperCase();
      const ss =
        admin_uin +
        "&" +
        uin +
        "&" +
        strid +
        "&" +
        appid +
        "&" +
        sign2 +
        "&" +
        ct;
      const sign1 = hex_md5(ss).toUpperCase();
      const sign = sign2.toUpperCase();
      this.demo.init({
        debug: true, // 日志是否输出 default false
        strid: "",
        // uin:Cookies.get('TQnumber') , // 账号 / 用户名 必填
        uin: Cookies.get("uin"),
        admin_uin: Cookies.get("admin_uin"), // 管理员账号
        appid: Cookies.get("appid"), // 唯一凭证
        access_token: Cookies.get("TQtoken_init"),
        // access_token:'645EAECEFF9EA9FF237C2FA430B2A1E3A9151E5C3035266D7701E4922AEA5F7F1B77B7762F7774511607EEA61E707FCA' , // 密文
        server_url: "https://vipedu.tq.cn" //如：http://vip.tq.cn
      });
    },
    // 批量导入
    customerManagerImport: function() {
      this.uploadOem = true;
      if (this.form.file != "") {
        this.$refs.uploadExcel.clearFiles();
        this.form.file = "";
      }
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: "警告",
        message: `只能选择 ${
          this.limitNum
        } 个文件，当前共选择了 ${files.length + fileList.length} 个`
      });
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      this.form.file = file.raw;
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (extension !== "xls") {
        this.$notify.warning({
          title: "警告",
          message: `只能上传Excel97-2004（即后缀是.xls）的文件`
        });
      }
      1;
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.$refs.uploadExcel.clearFiles();
      this.form.file = "";
      this.$notify.success({
        title: "成功",
        message: `文件上传成功,数据处理中,稍后在我的消息中查看！`
      });
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$notify.error({
        title: "错误",
        message: `文件上传失败`
      });
    },
    uploadFile() {
      let formData = new FormData();
      formData.append("file", this.form.file);
      axios
        .post(this.uploadUrl, formData, {
          "Content-Type": "multipart/form-data"
        })
        .then(res => {
          if (res.data.result == 1) {
            this.handleSuccess();
            let path = res.data.fileUrl;
            this.$api.student
              .schoolCustomerAddImport({ path: path })
              .then(res => {
                this.uploadOem = false;
                this.findPage(null);
              });
          } else {
            this.handleError();
          }
        });
    },
    // 删除上传列表操作
    handleRemove(file, fileList) {
      this.form.file = "";
    },

    // 下载模板
    downloadTmpl() {
      this.getStuTempl();
    },
    // 沟通形式
    get_contractType() {
      this.student_communication_type = JSON.parse(
        localStorage.getItem("studentContractType")
      );
    },
    // 获取时间
    dateFormat: function(time) {
      var date = new Date(time);
      var year = date.getFullYear();
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      var month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hours =
        date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      var minutes =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var seconds =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      // 拼接
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds
      );
    },
    get_dataTime() {
      let dateTime = new Date();
      // this.saveData.contractDate = this.dateFormat(dateTime);
      let mytime = dateTime.toLocaleTimeString("chinese", { hour12: false }); //获取当前时间
      this.mytime = mytime;
    },
    
    // 分中心远程搜索
    querySearchAsync(queryString, callback) {
      let restaurants = [{}];
      let results = "";
      this.$api.dropdown.branchcenter().then(res => {
        for (let i of res.branchCenterInfoList) {
          i.value = i.name; //将想要展示的数据作为value
        }
        restaurants = res.branchCenterInfoList;
        results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants;
        callback(results);
      });
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect(item) {
      this.queryBox.providerAgent = item.id;
    },
    // 销售人员远程搜索
    querySearchAsync2(queryString, callback) {
      let restaurants = [{}];
      let results = "";
      this.$api.dropdown.users({ userType: 3 }).then(res => {
        for (let i of res.userInfoList) {
          i.value = i.realName; //将想要展示的数据作为value
        }
        restaurants = res.userInfoList;
        results = queryString
          ? restaurants.filter(this.createFilter2(queryString))
          : restaurants;
        callback(results);
      });
    },
    createFilter2(queryString) {
      return restaurant => {
        return (
          restaurant.realName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect2(item) {
      this.queryBox.belongTo = item.id;
    },
    // 获取销售姓名
    get_sale_name() {
      this.$api.dropdown.users({ userType: 3 }).then(res => {
        this.belongTo = res.userInfoList;
      });
    },
    // 点击客户类型
    typeChange() {
      if (this.saveData.customerType == 5) {
        this.saveData.customerProgress = "8";
      }
    },
    // 点击客户进展
    progressChange(e) {
      if (this.saveData.customerProgress == 8) {
        this.saveData.customerType = "5";
      }
    },
    // 获取导入部门
    get_student_importDepartment() {
      this.$api.user
        .optionsList({ codeType: "student_import_department" })
        .then(res => {
          this.student_import_department = res.keyValueList;
        });
    },
    // 获取年级
    get_grade() {
      this.gradeCache = JSON.parse(localStorage.getItem("gradeCache"));
      console.log(this.gradeCache)
      this.subject_Options = JSON.parse(
        localStorage.getItem("studentSubject")
      );
    },

    // 获取沟通结果
    get_result() {
      this.student_result_options = JSON.parse(
        localStorage.getItem("progressResult")
      );
    },

    // 选择沟通结果
    contractResultChange() {
      if (this.saveData.contractResult != "") {
        // this.saveData.contractContent = "";
      }
    },
    // 获取跟进时候的客户进展
    get_track_progress() {
      this.$api.student.studentTrackProgress().then(res => {
        this.student_progress_options2 = res.keyValueList;
      });
    },
    // 报告类型
    get_reportType() {
      this.reportType_options = JSON.parse(
        localStorage.getItem("studentReportType")
      );
    },
    // 报告结果
    get_reportResult() {
      this.reportResult_options = JSON.parse(
        localStorage.getItem("studentReportResult")
      );
    },
     // 获取网推的下拉选项
    get_TG_options() {
      this.student_TGsource_options = JSON.parse(
        localStorage.getItem("studentTGsource")
      );
    },
    // 点击跟进里面报告结果 查看按钮
    handleReportResult() {
      // let params={
      //   phone:this.saveData.phone,
      //   reportType:this.saveData.reportType
      // }
      //  this.$router.push({
      //   path: "/studentInfo/toStudentReportPage",
      //   query: {
      //     phone:this.saveData.phone,
      //   reportType:this.saveData.reportType
      //   }
      // });
      // window.open=("/studentInfo/toStudentReportPage?phone=" +this.saveData.phone+"&reportType="+this.saveData.reportType,'blank')
      var url =
        "/studentInfo/toStudentReportPage?phone=" +
        this.saveData.phone +
        "&reportType=" +
        this.saveData.reportType;
      window.location.href = url;
    },
    studentSubject() {
      this.studentSubject = JSON.parse(
        localStorage.getItem("studentSubject")
      );
    },
    // 关闭索要弹窗
    colsePop(val){
      this.askingforShow=false
    },
    openAsking(){
      this.askingforShow=true
    },
    // 索要资源
    submitAsking(val){
      this.askingMessage=val
      this.askingloading=true
      this.$api.student.AskingFor({phone:val}).then(res=>{
        if(res.result==1){
          this.$message({
            message: res.msg,
            type: "success"
          });
          this.askingloading=false
          this.askingforShow=false
          this.isLoadingSuccess=true
        }else{
          this.$message({
            message: res.msg,
            type: "error"
          });
          this.askingloading=false
          this.isLoadingSuccess=false
        }
      })
    },
    // 查询角色信息
    queryUserRole() {
      this.$api.role.queryUserRole().then(res => {
        if (res.result == 1) {
          this.roleId = res.userInfo.roleId;
          if (
            this.roleId == this.roleId1 ||
            this.roleId == this.roleId2 ||
            this.roleId == this.roleId3 ||
            this.roleId == this.roleId4 ||
            this.roleId == this.roleId5
          ) {
            this.columns.map(item => {
              if (item.id) {
                item.customerSource = "customerSource";
              }
            });
            this.hideSome=true
          }
        }
      });
      
    },
    closeTrackingPop(){
      this.saveData.sparePhoneAdress=''
    } 
  },
  watch: {
    // student(oldID,newId) {
    //   this.student = newId;
    //   console.log("watch"+newId)
    // },
  },
  updated() {
    // this.findPage(null)
  },
  mounted() {
    this.findPage(null);
    this.get_student_data_from();
    this.get_student_progress();
    this.get_student_type();
    this.get_student_data_from_type();
    // this.wac();
    this.get_contractType();
    this.get_sale_name();
    this.get_dataTime();
    this.get_tqToken();
    this.get_student_importDepartment();
    this.get_studentContractType();
    this.get_grade_cache();
    this.get_grade();
    this.get_track_progress();
    this.get_student_track_type();
    this.get_reportType();
    this.get_reportResult();
    this.studentSubject();
    this.get_TG_options()
    this.queryUserRole();
    let _this = this; // 声明一个变量指向Vue实例this，保证作用域一致
    this.timer = setInterval(() => {
      _this.date = new Date(); // 修改数据date
    }, 1000);
  },
  destroyed: function() {
    this.demo.destroy();
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer); // 在Vue实例销毁前，清除我们的定时器
    }
  }
};
</script>
<style >
@import url("../../assets/queryBox.css");
</style>
<style lang='scss' scoped>
.reportBtn {
  color: #fff;
  background-color: #1a7284;
  border-color: #1a7284;
  display: inline-block;
  padding: 3px 10px;
  text-decoration: none;
  border-radius: 2px;
  margin-left: 22px;
  font-size: 12px;
}
.query-box {
  .el-row {
    .el-col i {
      font-style: normal;
      text-align: right;
      float: left;
      font-size: 14px;
      color: #606266;
      line-height: 40px;
      padding: 0 0 0 0;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
    }
  }
}
.query-box .slect-title,
.query-box .city-title {
  font-weight: bold !important;
}
.checked-person {
  display: block;
  float: left;
  margin-top: -10%;
  margin-left: 35%;
}
.second-contain-box {
  width: 95%;
  margin: 0 auto;
  .el-col {
    text-align: left;
    margin: 4px 0;
  }
  .el-row {
    margin: 0 0 !important;
  }
  .el-col i {
    font-style: normal;
    display: inline-block;
    margin-top: 10%;
  }
}
.inputbox {
  display: flex;
  flex-direction: row;
  span {
    display: block;
    width: 13%;
  }
  .el-input {
    width: 50%;
  }
  .el-textarea {
    float: left;
    margin-left: -4%;
  }
}
</style>
<style lang='scss'>
.myStudent .el-form-item {
  margin-bottom: 10px;
}
.myStudent{
  tbody{
    tr{
      td{
        height: 35px;
      }
    }
  }
}
.batchdistribution-pop {
  .el-dialog__header {
    text-align: left;
    margin-left: 10%;
    font-weight: bold;
  }
}
.red {
  color: red;
}
.query-boxstudent .el-input-group__prepend {
  font-weight: bold !important;
}
.stu-pop .el-select{
  width: 100%;
}
</style>
